/**
 * Created by AranciaCheng on 2017/5/6.
 */
import app from '../app';
/**
 * 提供登录、注册、忘记密码的最基本模块的服务
 * 1. 同步登陆验证信息
 * 2. 获取验证状态
 * 3. 设置验证状态
 * 4. 登陆
 * 5. 登出
 * 6. 注册账号
 * 7. 找回密码
 * 8. 获取证码(by email)
 */
app.factory('principal', ['$q', '$http','$state', function ($q, $http, $state) {
  var service = {};
  var _authenticated=false;

  service.async = ()=>
    $http({
      method:'GET',
      url:'/isUser',
    })

  service.getAuth = () => _authenticated;
  service.setAuth = s => _authenticated = s;
  service.login = (user,pw)=>
    $http({
      method:'POST',
      url:'/login',
      data:{
        username:user,
        password:pw
      }
    });


  service.logout = ()=>{
    $http({
      method:'POST',
      url:'/logout'
    }).then(()=>{
      service.setAuth(false);
      $state.go('login');
    },response=>{
      console.log(response.data)
    });
  }

  service.register = (user,pw,email,tel)=>
    $http({
      method: 'POST',
      url: '/register',
      data: {
        telephone: tel,
        mail: email,
        username: user,
        password: pw
      }
    }).then(()=>{
      alert('注册成功');
      $state.go('login');
    },response=>alert(`注册失败，${response.data}`));


  service.retrieve = (password,validateCode)=>
    $http({
      method:'POST',
      url:'/changepsd',
      data:{
        validatecode:validateCode,
        newpassword:password
      }
    })

  service.getValidateCode = email=>
    $http({
      method:'POST',
      url:'/getValidateCode',
      data:{
        email:email
      }
    });


  return service;
}])